import { constantRoutes } from '@/router'
// import { getRoutes } from '@/api/role'
import { Message } from 'element-ui'
import { allRouteComponentMap, asyncRoutes } from '@/router/index'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
/**
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}*/

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
/**
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}*/

/**
 * 后台路由数据转路由组件数组
 * @param routes
 * @returns {Array}
 */
export function transferDynamicRoutes(routes) {
  const routeVos = []
  if (!routes || routes.length === 0) return routeVos
  const length = routes.length
  for (let i = 0; i < length; i++) {
    const item = routes[i]
    let routeComponent
    if (item.componentUrl) {
      if (allRouteComponentMap[item.componentUrl]) {
        routeComponent = allRouteComponentMap[item.componentUrl]
      } else {
        routeComponent = allRouteComponentMap['@/views/error-page/404']
      }
    } else {
      routeComponent = null
    }
    const routeVo = { id: item.id, path: item.path, redirect: item.redirect ? item.redirect : 'noRedirect',
      name: item.name, alwaysShow: item.name === 'Permission',
      hidden: item.hidden,
      meta: { title: item.title,
        icon: item.icon,
        noCache: true
      },
      children: [],
      component: routeComponent
    }
    if (item.children.length > 0) {
      routeVo.children = transferDynamicRoutes(item.children)
    }
    routeVos.push(routeVo)
  }
  return routeVos
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, routeIds) {
    const routeIdMap = {}
    for (let i = 0; i < routeIds.length; i++) {
      routeIdMap[routeIds[i]] = routeIds[i]
    }
    return new Promise((resolve) => {
      // const dynamicRouteComponents = transferDynamicRoutes(dynamicRoutes)
      if (routeIds && routeIds.length > 0) {
        const dynamicRoutes = filterPermissionRoutes(routeIdMap, asyncRoutes)
        commit('SET_ROUTES', dynamicRoutes)
        resolve(dynamicRoutes)
      } else {
        // throw new Error('transferDynamicRoutes error')
        Message.error('transferDynamicRoutes error')
        resolve([])
      }
    })
  }
}

/**
 * 后台返回组装的routeIdMap获取过滤后的动态路由集合
 * @param {Object} routeIdMap
 * @param {Array} dynamicRoutes
 * @returns permissionRoutes
 */
export function filterPermissionRoutes(routeIdMap, dynamicRoutes) {
  const permissionRoutes = []
  for (let i = 0; i < dynamicRoutes.length; i++) {
    const routeItem = dynamicRoutes[i]
    if (routeIdMap[routeItem.id]) {
      const permissionRouteItem = {
        id: routeItem.id,
        path: routeItem.path,
        name: routeItem.name,
        alwaysShow: routeItem.alwaysShow != null && routeItem.alwaysShow,
        redirect: routeItem.redirect,
        meta: routeItem.meta,
        hidden: routeItem.hidden != null && routeItem.hidden,
        component: routeItem.component,
        children: []
      }
      permissionRoutes.push(permissionRouteItem)
      if (routeItem.children && routeItem.children.length > 0) {
        permissionRouteItem.children = filterPermissionRoutes(routeIdMap, routeItem.children)
      }
    }
  }
  return permissionRoutes
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
